"use client";
import useReactflowStore from '@/lib/store/useReactflowStore';
import { getBezierPath, EdgeText } from 'reactflow'

const foreignObjectSize = 40

export default function ButtonEdge({ id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, style = {}, data, markerEnd }: any) {
    const { deleteEdge } = useReactflowStore();
    const [edgePath, edgeCenterX, edgeCenterY] = getBezierPath({
        sourceX,
        sourceY,
        sourcePosition,
        targetX,
        targetY,
        targetPosition
    })

    const onDeleteEdge = (evt: any, id: string) => {
        evt.stopPropagation();
        deleteEdge(id);
    }

    return (
        <>
            <path id={id} style={style} className='react-flow__edge-path' d={edgePath} markerEnd={markerEnd} />
            {data && data.label && (
                <EdgeText
                    x={sourceX + 10}
                    y={sourceY + 10}
                    label={data.label}
                    labelStyle={{ fill: 'black' }}
                    labelBgStyle={{ fill: 'transparent' }}
                    labelBgPadding={[2, 4]}
                    labelBgBorderRadius={2}
                />
            )}
            <foreignObject
                width={foreignObjectSize}
                height={foreignObjectSize}
                x={edgeCenterX - foreignObjectSize / 2}
                y={edgeCenterY - foreignObjectSize / 2}
            >
                <div className='flex items-center justify-center w-[40px] h-[40px]'>
                    <button className='w-[20px] h-[20px] bg-[#eee] rounded-full text-sm hover:bg-secondary hover:text-white' onClick={(event) => onDeleteEdge(event, id)}>
                        ×
                    </button>
                </div>
            </foreignObject>
        </>
    )
}
